
package com.kugou.game.sdk.api.single;

import com.baidu.location.BDLocation;
import com.kugou.game.sdk.api.common.BasePlatform;
import com.kugou.game.sdk.api.common.BaseSDKConfig;
import com.kugou.game.sdk.api.common.IEventCode;
import com.kugou.game.sdk.api.common.IEventDataField;
import com.kugou.game.sdk.api.common.OnExitListener;
import com.kugou.game.sdk.api.common.OnPlatformEventListener;
import com.kugou.game.sdk.api.common.OnReceiveRankListListener;
import com.kugou.game.sdk.api.common.User;
import com.kugou.game.sdk.base.BaseCommonTitleFragmentActivity;
import com.kugou.game.sdk.core.GameManager;
import com.kugou.game.sdk.core.LocationManager;
import com.kugou.game.sdk.core.PlatformEventDispatcher;
import com.kugou.game.sdk.core.SDKControler;
import com.kugou.game.sdk.core.UserManager;
import com.kugou.game.sdk.interfaces.OnLoginListener;
import com.kugou.game.sdk.interfaces.OnSSOListener;
import com.kugou.game.sdk.statistics.StatCmd;
import com.kugou.game.sdk.statistics.StaticsManager;
import com.kugou.game.sdk.ui.activity.LoginActivity;
import com.kugou.game.sdk.ui.dialog.LoginDialog;
import com.kugou.game.sdk.ui.dialog.LoginDialog.OnClickAccountChangeListener;
import com.kugou.game.sdk.utils.AdHelper;
import com.kugou.game.sdk.utils.AppUncaughtExceptionHandler;
import com.kugou.game.sdk.utils.AppUtil;
import com.kugou.game.sdk.utils.DESUtil;
import com.kugou.game.sdk.utils.MD5Util;
import com.kugou.game.sdk.utils.NetWorkUtil;
import com.kugou.game.sdk.utils.SSOHelper;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import java.util.HashMap;

/**
 * 描述:单机SDK调用类
 * 
 * @author chenys
 * @since 2014-12-15 下午8:20:50
 */
public class KGPlatform extends BasePlatform {

    private static final int SDK_VERSION_CODE = 211;

    private static final String SDK_VERSION_NAME = "2.1.1";

    public static void init(Context context, BaseSDKConfig sdkConfig,
            OnPlatformEventListener eventListener) {
        SDKControler.init(context, sdkConfig, SDK_VERSION_CODE, SDK_VERSION_NAME, eventListener);
        // 启动推送服务
        AppUtil.startPushService(context, sdkConfig, SDK_VERSION_CODE, SDK_VERSION_NAME);
        // 请求位置信息
        LocationManager.getInstance(context).requestLocation();
    }

    private static LoginDialog mLoginingDialog;

    // 是否正在进入游戏
    private static boolean mEnteringGame;

    // 是否正在切换账号
    private static boolean mIsChangingAccount = false;

    private static boolean mEnteringGameByGuest = false;

    /**
     * 标准模式登录
     * 
     * @param activity
     */
    public static void enterGame(final Activity activity) {
        checkInit();
        checkDebugMode();
        // 防止重复登陆
        if (mEnteringGame) {
            return;
        }
        mEnteringGame = true;
        mIsChangingAccount = false;

        // 异常崩溃统计和日志上传处理
        Thread.setDefaultUncaughtExceptionHandler(new AppUncaughtExceptionHandler(activity));
        // 查询SP下的账号信息
        if (NetWorkUtil.isNetworkAvailable(activity)) {
            User user = UserManager.getInstance().getLastestUserDataOnSP();
            if (user == null) {
                // sp没有账号，显示登录进度对话框
                showLoginDialog(activity);
                // 2秒后进行游戏登录操作
                PlatformEventDispatcher.runOnUiThreadDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (mIsChangingAccount) {
                            return;
                        }
                        // 启用单点登陆
                        startSSOWithoutAccount();
                    }
                }, 2000);
            } else {
                if (user.isRegistered()) {
                    // sp有正式账号，显示登录进度对话框
                    showLoginDialog(activity);
                    // 2秒后进行游戏登录操作
                    final User temp = user;
                    PlatformEventDispatcher.runOnUiThreadDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if (mIsChangingAccount) {
                                return;
                            }
                            autoLogin(temp, activity);
                        }
                    }, 2000);
                } else {
                    enterGameSuccess(user);
                }
            }
        } else {
            // 没网络的情况，不用考虑sso登陆，直接游客登录
            enterGameByGuest();
        }
    }

    /**
     * 取不到缓存帐号,启动单点登陆
     */
    private static void startSSOWithoutAccount() {
        long appId = SDKControler.getAppId();
        String appKey = SDKControler.getAppKey();
        String packageName = SDKControler.getContext().getPackageName();
        String key = MD5Util.getMd5(appKey).substring(0, 8);
        String enPackageName = DESUtil.encrypt(packageName, key);
        HashMap<String, Object> hash = new HashMap<String, Object>();
        hash.put("appId", "" + appId);
        hash.put("appKey", appKey);
        hash.put("packageName", enPackageName);
        String jsonStr = AppUtil.convertHashMapToJson(hash);

        SSOHelper.startSingleSignOn(SDKControler.getContext(), jsonStr, new OnSSOListener() {

            @Override
            public void onComplete(String jsonStr) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);
                    String userName = jsonObj.getString("userName");
                    String token = jsonObj.getString("token");
                    long userId = jsonObj.getLong("userId");
                    loginByToken(userName, token);
                } catch (JSONException e) {
                    e.printStackTrace();
                    enterGameByGuest();
                }
            }

            @Override
            public void onError(int errorCode) {
                // 单点登陆失败,游客登录
                enterGameByGuest();
            }
        });
    }

    /**
     * 使用sso返回的token进行登陆
     * 
     * @param userName 用户名
     * @param token 用户令牌
     */
    private static void loginByToken(final String userName, final String token) {
        final long appId = SDKControler.getAppId();
        final OnLoginListener loginListener = new OnLoginListener() {
            @Override
            public void onSuccess(User user) {
                enterGameSuccess(user);
            }

            @Override
            public void onFailed(String errorMsg) {
                // 使用token登录失败，直接游客登录
                enterGameByGuest();
            }
        };
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 这里两个appId一致
                UserManager.getInstance().login(userName, token, appId, 1, appId, loginListener);
                mEnteringGame = false;
            }
        }).start();
    }

    /**
     * 游客模式登录
     */
    public static void enterGameByGuest() {
        checkInit();
        checkDebugMode();
        // 防止重复登陆
        if (mEnteringGameByGuest) {
            return;
        }
        Log.d(SDKControler.KUGOU_SDK_TAG, ">>>>>>>>>>>>>调用游客登录接口");

        mEnteringGameByGuest = true;
        mIsChangingAccount = false;

        Context context = SDKControler.getContext();
        // 异常崩溃统计和日志上传处理
        Thread.setDefaultUncaughtExceptionHandler(new AppUncaughtExceptionHandler(context));

        User user = UserManager.getInstance().getSingleUserDataForGuest(context);
        enterGameSuccess(user);

    }

    /**
     * 显示登录加载框
     */
    private static void showLoginDialog(final Activity activity) {
        mLoginingDialog = LoginDialog.initDialog(activity);
        User user = UserManager.getInstance().getLastestUserDataOnSP();
        if (user != null && user.isRegistered()) {
            mLoginingDialog.setLoginUserName(user.getAccountName());
        }
        mLoginingDialog.setOnClickAccountChangeListener(new OnClickAccountChangeListener() {
            @Override
            public void clickChangeAccount() {
                mIsChangingAccount = true;
                mEnteringGame = false;
                mEnteringGameByGuest = false;

                mLoginingDialog.dismiss();

                // 跳转到登录界面
                Intent intent = new Intent(activity, LoginActivity.class);
                intent.putExtra(BaseCommonTitleFragmentActivity.FROM_ACTION_KEY,
                        BaseCommonTitleFragmentActivity.FROM_BEFORE_ENTER_GAME_LOGIN);
                activity.startActivity(intent);
            }
        });
        mLoginingDialog.show();
    }

    private static void autoLogin(final User user, final Activity activity) {
        // 自动登录
        final String userName = user.getAccountName();
        final String password = user.getPassword();
        final long appId = SDKControler.getAppId();
        final long tAppId = user.getKugouTokenAppId();
        final String kugouToken = user.getKugouToken();

        final OnLoginListener listener = new OnLoginListener() {
            @Override
            public void onSuccess(User newUser) {
                enterGameSuccess(newUser);
            }

            @Override
            public void onFailed(String errorMsg) {
                enterGameSuccess(user);
                // enterGameFailed(user, errorMsg);
            }

        };
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (TextUtils.isEmpty(password)) {
                    // 密码为空，使用token登陆
                    UserManager.getInstance().login(userName, kugouToken, appId, 1, tAppId,
                            listener);
                } else {
                    // 使用密码登陆
                    UserManager.getInstance().login(userName, password, appId, 0, 0, listener);
                }

                mEnteringGame = false;
            }

        }).start();
    }

    private static void enterGameSuccess(User user) {
        UserManager.getInstance().setCurrentUser(user);
        if (mIsChangingAccount) {
            return;
        }
        mEnteringGame = false;
        mEnteringGameByGuest = false;

        if (mLoginingDialog != null && mLoginingDialog.isShowing()) {
            mLoginingDialog.dismiss();
        }

        // 发送进入游戏回调
        int eventCode = IEventCode.ENTER_GAME_SUCCESS;
        Bundle data = new Bundle();
        data.putSerializable(IEventDataField.EXTRA_USER, user);
        PlatformEventDispatcher.sendEvent(eventCode, data);
        AppUtil.handleActionsAfterLoginSuccess(eventCode);

        // 发送登录游戏统计(单机登录游戏和进入游戏是同一个)
        Log.d(SDKControler.KUGOU_SDK_TAG, ">>>>>>>>>>>>>>发送登录游戏成功统计");
        StaticsManager.sendCommonStatis(StatCmd.CMD_APP_LOGIN_SUCCESS);
    }

    private static Handler uiHanler = new Handler(Looper.getMainLooper());

    /**
     * 请求贴片广告信息
     */
    public static void requestAdInfo(final Activity activity) {
        Log.d(SDKControler.KUGOU_SDK_TAG, ">>>>>>>>>>>>>调用请求单机广告接口");
        uiHanler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (NetWorkUtil.isNetworkAvailable(SDKControler.getContext())
                        && !AdHelper.getInstance(activity).isLoadAdInfoOk()) {
                    // AdHelper的AsyncImageLoader类需要在UI线程初始化
                    AdHelper.getInstance(activity).requestAdInfo();
                }
            }
        }, 500);
    }

    /**
     * 退出游戏
     * 
     * @param activity
     * @param listener 退出游戏的回调接口
     */
    public static void exitGame(final Activity activity, final OnExitListener listener) {
        uiHanler.post(new Runnable() {
            @Override
            public void run() {
                try {
                    // 如果网络正常且加载广告成功，才弹窗
                    if (NetWorkUtil.isNetworkAvailable(SDKControler.getContext())) {
                        AdHelper.getInstance(activity).showExitAdDialog(activity, listener);
                    } else {
                        if (listener != null) {
                            try {
                                listener.exitGame(0);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        Log.d(SDKControler.KUGOU_SDK_TAG, ">>>>>>>>>>>>>调用退出游戏接口");
    }

    /**
     * 获取排行榜信息
     * 
     * @param score 游戏分数
     * @param account 用户名
     * @param role 角色名
     * @param listener 获取排行榜信息的回调接口
     */
    public static void getRankingList(int score, String role, OnReceiveRankListListener listener) {
        checkInit();
        Context context = SDKControler.getContext();
        if (!NetWorkUtil.isNetworkAvailable(context)) {
            Toast.makeText(context, "请检查您的网络连接", Toast.LENGTH_SHORT).show();
            return;
        }

        final int sc = score;
        String acc = "";
        try {
            acc = getCurrentUser().getAccountName();
        } catch (Exception e) {
            e.printStackTrace();
        }
        final String ro = role;
        final OnReceiveRankListListener slistener = listener;

        final Handler handler = new Handler(Looper.getMainLooper()) {
            @Override
            public void handleMessage(Message msg) {
                String result = (String) msg.obj;
                if (slistener != null) {
                    slistener.handleResult(result);
                }
            }
        };

        final String name = acc;
        new Thread(new Runnable() {
            @Override
            public void run() {
                String result = requestGameRankList(sc, name, ro);
                Message message = new Message();
                message.obj = result;
                handler.sendMessage(message);
            }
        }).start();
    }

    // 请求游戏排行榜数据
    private static String requestGameRankList(int score, String account, String role) {
        BDLocation location = LocationManager.getInstance(SDKControler.getContext()).getLocation();
        if (location == null) {
            return "请求位置信息失败";
        }
        return GameManager.requestGameRankList(location, score, account, role);
    }

}
